package com.jiao.datasource.track;

import cn.hutool.json.JSONArray;
import com.jiao.datasource.parse.SQLCommand;
import com.jiao.datasource.parse.WriteSQLUnit;

import java.sql.SQLException;
import java.sql.Statement;

/**
 * 记录sql细节.
 * @Author Vincent.jiao
 * @Date 2022/5/13 11:14
 */
public class RecordSQLDetail extends SQLExecTrack {
    public static void recordParam(int index, Object val) {
        getCurrExceSQL().getSqlUnit().setParams(index, val);
    }

    public static void recordSql(Statement ps, String sql)
            throws SQLException {
        setSQLCommand(new SQLCommand(ps.getConnection(), ps, sql));
    }

    /**
     * 记录标识为批量.
     */
    public static void recordAddBatch(String sql) {
        //标记批量, add 批量的就以集合格式添加
        String oldSql = getCurrExceSQL().getSqlUnit().setBatch(true).getSql();

        JSONArray array = new JSONArray(oldSql);
        array.add(sql);
        getCurrExceSQL().getSqlUnit().setSql(array.toString());
    }

    /**
     * 记录标识为批量.
     */
    public static void recordAddBatch() {
        //标记批量
        getCurrExceSQL().getSqlUnit().setBatch(true).setBatchParams();
    }

    public static void setCount(int count) {
        SQLCommand sqlCommand = getCurrExceSQL();
        if(sqlCommand.getSqlUnit() instanceof WriteSQLUnit) {
            ((WriteSQLUnit) sqlCommand.getSqlUnit()).setCount(count);
        }
    }
}
